<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    public function homeData()
    {
        return apiResponse(data: [
            'users' => $this->getCountByDay('users',30),
            'count_items' => $this->getItemNum(),
        ]);
    }

    /**
     * 获取最近几天的统计数据
     * @param $table
     * @param $day
     * @return array
     */
    protected function getCountByDay($table,$day): array
    {
        $count = DB::table($table)
            ->whereBetween('created_at', [Carbon::today()->subDays($day), Carbon::now()])
            ->select([DB::raw("DATE_FORMAT(created_at,'%m-%d') as date"), DB::raw('COUNT("*") as value')])
            ->groupBy('date')
            ->orderBy('date')
            ->get()->pluck('value','date');
        $date = array();
        $data = [];
        for ($i = 0; $i < $day; $i++) {
            $date[] = Carbon::today()->subDays($day-$i-1)->format('m-d');
        }
        foreach ($date as $v){
            $data[$v] = $count[$v] ?? 0;
        }
        return $data;
    }
    /**
     * 获取各项总数
     */
    protected function getItemNum(){
        return [
            'user' => DB::table('users')->count()
        ];
    }
}
